<template>
  <div>
   <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card >
      <el-alert
      title="注意:只允许为第三级分类设置相关参数"
      type="warning"
      :closable="false"
      show-icon>
    </el-alert>
    <div style="margin :15px 0">
      选择商品分类:
      <!-- options可选择的商品数据 v-model="casscaderValue"根据我的value拿到我改变化后的值-->
      <!--  props是一个对象，可以存很多东西可以具体的渲染某个字段，必须写label，不定义label具体渲染的字段，会全部渲染-->
        <el-cascader
        v-model="casscaderValue"
        :options="goodsCates"
        :props="cascaderPrors"
        @change="cascaderHandleChange">
      </el-cascader>
      </div>
      <el-tabs v-model="activeName" @tab-click="tabshandleClick">
          <!-- 双向绑定根据我name的变化监听到我选的动态还是静态  -->
        <el-tab-pane label="动态参数" name="many">
        <!-- 按钮 点击添加按钮让我对话框显示-->
          <el-button  type="primary" :disabled="isDisable" size="mini" @click="addParamsDialogVisble =true" >添加按钮</el-button>
          <!--:daata 动态绑定我动态数据 -->
          <el-table :data="manyTableDate" border stripe>
            <!--  type="expand"展开-->
            <el-table-column type="expand">
              <!-- 作用域插槽，拿到我这一行数据 -->
              <!-- 循环这一行scope.row拿到这一行数据这一行数据对内部attr_vals进行循环 -->
              <!-- inputValue当前这一行输入框的值 -->
              <template slot-scope="scope">
                <el-tag @close="removeTag(scope.row,index)"  closable v-for="(item, index) in scope.row.attr_vals" :key="index"> {{item}}</el-tag>
                <el-input
                class="scope.row.input-new-tag"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"
              >
              </el-input>
            <!-- 点击newtag触发showtag事件函数标签，让我拿到这一行的数据 -->
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="attr_name" label="参数名称"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="showEditDialog(scope.row)" icon="el-icon-edit" size="mini">修改</el-button>
              <el-button type="danger" @click="showDelete(scope.row)" icon="el-icon-delete" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
        <!-- 注册点击事件让我对话框显示 -->
      <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" :disabled="isDisable" size="mini" @click="addParamsDialogVisble =true">添加按钮</el-button>
          <el-table :data="onlyTableDate" border stripe>
            <el-table-column type="expand">
            <template slot-scope="scope">
              <!-- 把数据上每一个值在渲染到页面   attr_vals数组返回的字符串，每个都已扣个分割，所有属性上的参数， 小tag框-->
              <el-tag @close="removeTag(scope.row, index)"  closable v-for="(item, index) in scope.row.attr_vals" :key="index"> {{item}}</el-tag>
              {{scope.row.attr_vals}}
              <el-input
              class="scope.row.input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm(scope.row)"
              @blur="handleInputConfirm(scope.row)"
            >
            <!-- 我输入框失去焦点点击回车触发的事件函数 -->
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
            </template>
          </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" @click="showEditDialog(scope.row)" icon="el-icon-edit" size="mini">修改</el-button>
                <el-button type="danger" @click="showDelete(scope.row)" icon="el-icon-delete" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 动态对话框 -->
    <el-dialog
      @close="Addmitpamams"
      :title="'添加'+ addParamsText"
      :visible.sync="addParamsDialogVisble"
      width="50%">
      <!-- :model="addParamsForm" 绑定表单数据 -->
     <el-form ref="addParamsFormRef" :model="addParamsForm" :rules="addParamsRules"   label-width="80px">
      <el-form-item :label="addParamsText" prop="attr_name">
        <!-- prop绑定校验规则 -->
        <el-input v-model="addParamsForm.attr_name"></el-input>
      </el-form-item>
     </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsDialogVisble = false">取 消</el-button>
    <el-button type="primary" @click="submitAddParams">确 定</el-button>
  </span>
</el-dialog>
<!-- 静态属性对会话框 -->
<!-- attr_name存储输入框里的值 -->
    <el-dialog
      :title="'修改'+ addParamsText"
      :visible.sync="editParamsDialogVisble"
      width="50%">
      <!-- :model="addParamsForm" 绑定表单数据 -->
     <el-form ref="editParamsFormRef" :model="editaddParamsForm" :rules="addParamsRules"   label-width="80px">
      <el-form-item :label="addParamsText" prop="attr_name">
        <!-- prop绑定校验规则 -->
        <el-input v-model="editaddParamsForm.attr_name"></el-input>
      </el-form-item>
     </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editParamsDialogVisble = false">取 消</el-button>
    <el-button type="primary" @click="subitEditParams">确 定</el-button>
  </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 添加参数属性表单
      addParamsForm: {
        attr_name: ''
      },
      // 控制输入框和newtag按钮的按需显示
      inputVisible: false,
      inputValue: '',
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      editaddParamsForm: {
        attr_name: ''
      },
      editParamsDialogVisble: false,
      addParamsDialogVisble: false,
      // 存储动态的值
      manyTableDate: [],
      // 存储静态的值
      onlyTableDate: [],
      goodsCates: [],
      casscaderValue: [],
      cascaderPrors: {
        expandTrigger: 'hover',
        value: 'cat_id',
        // 把选的id存储来
        label: 'cat_name'
      },
      activeName: 'many'
      // 双向绑定点击是many还是only,默认的是many
    }
  },

  created () {
    this.getGoodsCate()
  },
  // 计算属性,将逻辑进行抽离,让代码看起来更简洁,清晰
  computed: {
    // 如果我没选择三级分类数据,让isDisable按钮禁用
    isDisable () {
      return this.casscaderValue.length !== 3
    },
    // 我三级分类数据
    cateId () {
      if (this.casscaderValue.length !== 3) {
        return null
      }
      return this.casscaderValue[2]
    },
    addParamsText () {
      return this.activeName === 'only' ? '静态属性' : '动态属性'
    }
  },
  methods: {
    // 拿到后台返回来的数据
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.console.error('获取失败')
      this.goodsCates = res.data
    },
    cascaderHandleChange () {
      this.getParams()
    },
    tabshandleClick () {
      this.getParams()
    },
    // 重新获取表格参数数据
    // 判断我选择三级表单，如果是一级二级返回
    async getParams () {
      if (this.casscaderValue.length !== 3) {
        this.casscaderValue = []
        this.manyTableDate = []
        this.onlyTableDate = []
        return
      }
      // cateid是我第三级的数据
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
          // 是静态还是动态
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // item是遍历我res.data的数据,因为我静态和动态用的是一个数据,所以对一个进行遍历操作就行
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableDate = res.data
      } else {
        this.manyTableDate = res.data
      }
      console.log(res)
    },
    submitAddParams () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.getParams()
        this.$message.success('创建成功')
        this.addParamsDialogVisble = false
      })
    },
    Addmitpamams () {
      this.$refs.addParamsFormRef.resetFields()
    },
    showEditDialog (row) {
      this.editParamsDialogVisble = true
      console.log(row)
      this.editaddParamsForm = { ...row }
    },
    subitEditParams () {
      this.$refs.editParamsFormRef.validate(async flag => {
        if (!flag) return
        // attrId 当前修改这一项的id this.editaddParamsForm.attr_id
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editaddParamsForm.attr_id}`, {
          attr_name: this.editaddParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getParams()
        this.editParamsDialogVisble = false
      })
    },
    showDelete (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    // 输入框失去焦点或者点击回车
    async handleInputConfirm (row) {
      console.log(row)
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // console.log('ok可以添加了')
      // 将数据追加给attr_vals同步页面
      row.attr_vals.push(row.inputValue)
      // row.attr_vals当前属性所有参数
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      row.inputValue = false
      row.inputValue = ''
    },
    // 循环attr_vals数组,数组多一个页面就多一个
    // 点击newtag标签
    showInput (row) {
      // 拿到我当前的输入框等于true
      row.inputVisible = true
      // vue数据驱动是异步的，会渲染tag标签为true但这一行的数据还没渲染到页面，$nextTick是处理异步问题dom元素都（等我这个函数都加载完才调用）
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async removeTag (row, index) {
      console.log('王琪梦笨蛋')
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    }
  }
}
</script>
<style scoped lang='less'>
.el-tag{
  margin: 7px;
}
</style>
